package com.acmedcare.framework.exchange.center.core.application;

import com.acmedcare.framework.exchange.center.core.PluginMetadata;
import com.acmedcare.framework.exchange.center.core.integration.SpringBootLauncher;
import com.acmedcare.framework.exchange.center.core.metadata.IDataApplication;
import com.acmedcare.framework.exchange.center.core.resolve.PathResolveFactory;
import com.acmedcare.framework.exchange.center.entity.dto.Hdfs;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RemoteApplicationResolver extends BaseApplicationResolver {

  private final Hdfs hdfs;

  public RemoteApplicationResolver(Hdfs hdfs) {
    this.hdfs = hdfs;
  }

  @Override
  public void resolve(PluginMetadata metadata) {

    try {

      String path = new PathResolveFactory(hdfs)
          .getPathResolve(metadata.getJarPath(), metadata.getJarName(), hdfs.getRootPath())
          .resolve();
      metadata.setJarPath(path);

      if (!metadata.getSpringBoot()) {
        File jarFile = new File(metadata.getJarPath());
        URL uri = jarFile.toURI().toURL();
        ClassLoader classLoader = new URLClassLoader(new URL[]{uri},
            IDataApplication.class.getClassLoader());
        metadata.setClassLoader(classLoader);
        Thread.currentThread().setContextClassLoader(classLoader);
      } else {
        new Thread(() -> {
          try {
            SpringBootLauncher.init(path, metadata);
          } catch (Exception e) {
            log.error(String
                .format("插件:%s，版本:%s，加载失败，失败原因:%s", metadata.getName(), metadata.getVersion(),
                    e.getMessage()),e);
          }
        }).run();

      }
      super.resolve(metadata);
    } catch (Exception e) {

      log.error("插件加载失败，插件名称:" + metadata.getName(), e);
    }
  }
}
